package cn.alex.sso.project.sync.event;

import cn.alex.sso.project.entity.SysClient;
import cn.alex.sso.project.entity.SysUser;
import cn.alex.sso.project.entity.params.EditSysUserStatus;
import cn.alex.sso.project.service.SysClientService;
import cn.alex.sso.project.sync.module.UserDataSyncModule;
import cn.hutool.extra.spring.SpringUtil;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户数据同步
 *
 * @author Alex
 * @date 2024/12/1 02:31
 */
public class UserAbstractDataSyncEvent extends AbstractDataSyncEvent {
    public UserAbstractDataSyncEvent(Object source, Object data, UserDataSyncModule.Trigger trigger) {
        super(source, data, UserDataSyncModule.MODULE.getValue(), trigger.getValue());
    }

    @Override
    public List<Long> customSyncClient() {
        String trigger = getTrigger();

        if (UserDataSyncModule.Trigger.ADD.getValue().equals(trigger) || UserDataSyncModule.Trigger.EDIT.getValue().equals(trigger)) {
            SysUser data = (SysUser) getData();
            return getAllowListByUserId(data.getId());
        } else if (UserDataSyncModule.Trigger.EDIT_STATUS.getValue().equals(trigger)) {
            EditSysUserStatus data = (EditSysUserStatus) getData();
            return getAllowListByUserId(data.getId());
        } else if (UserDataSyncModule.Trigger.DELETE.getValue().equals(trigger)) {
            Long data = (Long) getData();
            return getAllowListByUserId(data);
        }

        return null;
    }

    @Override
    public Object customProcess(Object data) {
        return data;
    }

    /**
     * 获取用户允许访问的应用ID集合
     *
     * @param id 用户ID
     * @return List<Long>
     */
    public List<Long> getAllowListByUserId(Long id) {
        SysClientService clientService = SpringUtil.getBean(SysClientService.class);
        List<SysClient> clientList = clientService.getAllowListByUserId(id);
        return clientList.stream().map(SysClient::getId).collect(Collectors.toList());
    }
}
